#!coding=utf-8
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import *
from django.views.decorators.csrf import csrf_exempt
from django.db import transaction
from models import *

from util.form_util import *
from itertools import chain,islice
import json
import datetime


@csrf_exempt
@transaction.commit_on_success
def enterLayout(request):

    _enterPrise = request.session.get('ep', None)

    if request.method == 'GET':
        if not _enterPrise:
            return HttpResponse('当前用户信息错误')

        _mdcList = MapDataCategory.objects.all()
        _mdcNames = []

        _points,_centerPoint,_extent = _enterPrise.getGeoData()

        if not _points and not _centerPoint and not _extent:
            _points,_centerPoint,_extent = '[]','[]','[]'

        _pPoints,_pCenterPoint = _enterPrise.getParkGeoData()

        if not _pPoints and not _pCenterPoint:
            _pPoints,_pCenterPoint = '[]','[]'

        for _mdc in _mdcList:
            _tmp = {}
            _tmp['name'] = _mdc.name
            _tmp['key'] = _mdc.key
            _mdcNames.append( _tmp )

        _mapData = [
            {'name':'production','url':'/facilities/productAreaGeo/'},
            {'name':'storage','url':'/facilities/storageAreaGeo/'}
        ]

        _tmpData = { 
            'mdcNames' : _mdcNames, 
            'mapData': _mapData,
            'e':{
                'centerPoint': _centerPoint,
                'points': _points
            },
            'p':{
                'centerPoint': _pCenterPoint,
                'points': _pPoints,
                'extent': _enterPrise.park.geo_extent
            },
            'enterprise':_enterPrise
        }

        return render_to_response('enterprise/map/enterlayout.html', _tmpData, context_instance=RequestContext(request))
    
    if request.method == 'POST':
        _form = request.POST
        d_type = _form.get('type',None)
        
        try:
            if d_type == '1':
                obj = ProductArea()
                d_type_name = '生产区'
                d_type_key = 'production'
                auto_wear(request, obj, 'enterprise_facilities', 'ProductArea')

            if d_type == '2':
                obj = StorageArea()
                d_type_name = '贮罐区'
                d_type_key = 'storage'
                auto_wear(request, obj, 'enterprise_facilities', 'StorageArea')

            _mdc = MapDataCategory.objects.filter(name = d_type_name)

            if len(_mdc) > 0:
                _mdc = _mdc[0]
            else:
                _mdc = MapDataCategory(name = d_type_name,key = d_type_key)
                _mdc.save()

            _points = _form.get('points',None)
            center_point = _form.get('center',None)

            if not _points:
                result = {'error':'未选择地图'}
                return HttpResponse(json.dumps(result))

            _m = MapData(points = _points, mapData_type = _mdc,enterprise_id = _enterPrise.id,center_point = center_point )
            _m.save()

            fill = request.session.get('fill', None)
            app_k = 'S'
            app_name = d_type_name
            app_s = Application_status.objects.filter(app_name=app_name, fill_id = fill.id)

            if len(app_s) > 0:
                app_s = app_s[0]
                app_s.app_status = u'未确认'
                app_s.save()
            else:
                app_s = Application_status(app_name=app_name, fill_id = fill.id, app_status=u'未确认', app_key=app_k, app_submit_time=datetime.datetime.now(), enterprise=_enterPrise)
                app_s.save()

            obj.app_status = app_s
            obj.enterprise = _enterPrise
            obj.mapdata = _m
            obj.submit_type = 1
            obj.save()
            checkAppStatus(request, 2)
        except Exception,e:
            transaction.rollback()
            result = {'error':e.message if '' else (e.__str__()) }
            return HttpResponse(json.dumps(result))
        else:
            result = {'success':'数据添加成功!'}
            return HttpResponse(json.dumps(result))

#数据提交
@transaction.commit_on_success
def checkAppStatus(request, _type):
    try:
        _enterPrise = request.session.get('ep')
            
        _type = int(_type)

        if _type == 1:
            query = ProductArea.objects.all()
            app_name = u'生产区'
        elif _type == 2:
            query = StorageArea.objects.all()
            app_name = u'贮罐区'
        else:
            return HttpResponse(u'禁止访问')

        fill = request.session.get('fill', None)
        
        app_s = Application_status.objects.filter(app_name=app_name, fill_id = fill.id)[0]

        query = query.filter(enterprise = _enterPrise, app_status = app_s)

        query_sub2 = query.filter(submit_type = 2)

        count_q = len(query)

        count_s2 = len(query_sub2)

        if count_q == 0:
            app_s.app_status = '未确认'
        elif count_q > count_s2:
            app_s.app_status = '未确认'
        elif count_q == count_s2:
            app_s.app_status = '已确认'
        
        app_s.save()

    except Exception,e:
        print e.message

def productAreaList(request):
    _enterPrise = request.session.get('ep')

    if request.method == "GET":

        year = request.GET.get('y', None)
        month = request.GET.get('m', None)

        try:
            fill = request.session.get('fill', None)
            app_k = 'S'
            app = Application_status.objects.filter(app_name='生产区', fill_id=fill.id)
                
            if len(app) > 0:
                app = app[0]
            else:
                app = Application_status(app_name='生产区', fill_id=fill.id, app_status=u'未确认', app_key=app_k, app_submit_time=datetime.datetime.now(), enterprise=_enterPrise)
                app.save()
            
            ps_app = ProductArea.objects.filter(submit_type = 2, enterprise = _enterPrise, app_status = app)
            ps_none = ProductArea.objects.filter(submit_type = 1, enterprise = _enterPrise, app_status = app)

            ps_query = chain(ps_app, ps_none)
            ps = []

            for obj in ps_query:
                ps.append(obj)

            paginator = Paginator(ps, 10)
            page = request.GET.get('page')
            ps = paginator.page(page)
        except PageNotAnInteger:
            ps = paginator.page(1)
        except EmptyPage:
            ps = paginator.page(paginator.num_pages)
        except Exception as e:
            return HttpResponse("非法请求\n\n")

        return render_to_response('enterprise/facilities/production/productAreaList.html', { 'ps':ps, 'status':fill.status, 'paginator':paginator } ,context_instance=RequestContext(request))

@csrf_exempt
def productAreaAdd(request):
    _enterPrise = request.session.get('ep')
    if request.method == 'GET':
        return render_to_response('enterprise/facilities/production/productAreaAdd.html', context_instance=RequestContext(request))

    if request.method == 'POST':
        p = ProductArea()
        auto_wear(request, p, 'enterprise_facilities', 'ProductArea')

        key = request.GET.get('key',None)

        if not key:
            p.submit_type = 2
        else:
            p.submit_type = 1

        fill = request.session.get('fill', None)
        app_k = 'S'
        app_name = u'生产区'
        app_s = Application_status.objects.filter(app_name=app_name, fill_id = fill.id)

        if len(app_s) > 0:
            app_s = app_s[0]
            app_s.app_status = u'未确认'
            app_s.save()
        else:
            app_s = Application_status(app_name=app_name, fill_id = fill.id, app_status=u'未确认', app_key=app_k, app_submit_time=datetime.datetime.now(), enterprise=_enterPrise)
            app_s.save()

        p.app_status = app_s
        p.enterprise = _enterPrise
        p.save()

        checkAppStatus(request, 1)
        return HttpResponseRedirect('/facilities/productAreaList/')

@csrf_exempt
def productAreaEdit(request, id):
    _enterPrise = request.session.get('ep')
    if request.method == 'GET':
        p = ProductArea.objects.get(id = id)
        return render_to_response('enterprise/facilities/production/productAreaAdd.html', { 'p':p }, context_instance=RequestContext(request))

    if request.method == 'POST':
        p = ProductArea.objects.get(id = id)
        auto_wear(request, p, 'enterprise_facilities', 'ProductArea')

        key = request.GET.get('key',None)

        if not key:
            p.submit_type = 2
        else:
            p.submit_type = 1

        p.enterprise = _enterPrise
        p.save()

        checkAppStatus(request, 1)
        return HttpResponseRedirect('/facilities/productAreaDetail/%s' % p.id)

def productAreaDetail(request, id):
    try:
        p = ProductArea.objects.get(id = id)

        ps = Production.objects.filter(product_area = p.id)

        paginator = Paginator(ps, 10)
        page = request.GET.get('page')
        ps = paginator.page(page)
    except PageNotAnInteger:
        ps = paginator.page(1)
    except EmptyPage:
        ps = paginator.page(paginator.num_pages)
    except Exception as e:
        return HttpResponse("非法请求\n\n"+ e.message)

    return render_to_response('enterprise/facilities/production/productAreaDetail.html', { 'p':p, 'ps':ps }, context_instance=RequestContext(request))

@transaction.commit_on_success
def productAreaDel(request, id):
    try:
        p = ProductArea.objects.get(id = id)
        ps = Production.objects.filter(product_area = p.id)

        for pi in ps:
            pi.delete()

        p.delete()

        checkAppStatus(request, 1)
        return HttpResponseRedirect('/facilities/productAreaList/')

    except Exception,e:
        transaction.rollback()
        result = {'error':e.message if '' else (e.__str__()) }
        return HttpResponse(simplejson.dumps(result))

def productAreaItems(request, id):
    if request.method == "GET":
        try:
            ps = Production.objects.filter(product_area = id)

            paginator = Paginator(ps, 10)
            page = request.GET.get('page')
            ps = paginator.page(page)
        except PageNotAnInteger:
            ps = paginator.page(1)
        except EmptyPage:
            ps = paginator.page(paginator.num_pages)
        except Exception as e:
            return HttpResponse("非法请求\n\n"+ e.message)

        return render_to_response('enterprise/facilities/production/productionList.html', { 'ps':ps, 'status':fill.status, 'paginator':paginator, 'pid':id } ,context_instance=RequestContext(request))

def productionList(request, id):
    _enterPrise = request.session.get('ep')
    if request.method == "GET":
        try:
            ps = ProductArea.objects.filter(product_area = id)

            paginator = Paginator(ps, 10)
            page = request.GET.get('page')
            ps = paginator.page(page)
        except PageNotAnInteger:
            ps = paginator.page(1)
        except EmptyPage:
            ps = paginator.page(paginator.num_pages)
        except Exception as e:
            return HttpResponse("非法请求\n\n"+ e.message)

        return render_to_response('enterprise/facilities/production/productionList.html', { 'ps':ps, 'paginator':paginator, 'pid':id } ,context_instance=RequestContext(request))

@csrf_exempt
def productionAdd(request, id):
    _enterPrise = request.session.get('ep')
    if request.method == 'GET':
        return render_to_response('enterprise/facilities/production/productionEdit.html', { 'pid':id }, context_instance=RequestContext(request))

    if request.method == 'POST':
        p = Production()
        auto_wear(request, p, 'enterprise_facilities', 'Production')
        p.product_area = ProductArea.objects.get(id = id)
        p.save()
        return HttpResponseRedirect('/facilities/productAreaDetail/%s' % id)

@csrf_exempt
def productionEdit(request, id):
    _enterPrise = request.session.get('ep')
    if request.method == 'GET':
        p = Production.objects.get(id = id)
        return render_to_response('enterprise/facilities/production/productionEdit.html', { 'p':p }, context_instance=RequestContext(request))

    if request.method == 'POST':
        p = Production.objects.get(id = id)
        auto_wear(request, p, 'enterprise_facilities', 'Production')
        p.save()
        return HttpResponseRedirect('/facilities/productAreaDetail/%s' % p.product_area.id)

def productionDetail(request, id):
    p = Production.objects.get(id = id)
    return render_to_response('enterprise/facilities/production/productionDetail.html', {'p':p }, context_instance=RequestContext(request))

def productionDel(request, id):
    p = Production.objects.get(id = id)
    p.delete()
    return HttpResponseRedirect('/facilities/productAreaDetail/%s' % p.product_area.id)



def storageAreaList(request) :
    _enterPrise = request.session.get('ep')

    if request.method == "GET":
        try:
            fill = request.session.get('fill', None)
            app_k = 'S'
            app = Application_status.objects.filter(app_name='贮罐区', fill_id=fill.id)
                
            if len(app) > 0:
                app = app[0]
            else:
                app = Application_status(app_name='贮罐区', fill_id=fill.id, app_status=u'未确认', app_key=app_k, app_submit_time=datetime.datetime.now(), enterprise=_enterPrise)
                app.save()
            
            sas_app = StorageArea.objects.filter(submit_type = 2, enterprise = _enterPrise, app_status = app)
            sas_none = StorageArea.objects.filter(submit_type = 1, enterprise = _enterPrise, app_status = app)

            sas_query = chain(sas_app, sas_none)
            sas = []

            for obj in sas_query:
                sas.append(obj)

            paginator = Paginator(sas, 10)
            page = request.GET.get('page')
            sas = paginator.page(page)
        except PageNotAnInteger:
            sas = paginator.page(1)
        except EmptyPage:
            sas = paginator.page(paginator.num_pages)
        except Exception as e:
            return HttpResponse("非法请求\n\n"+ e.message)

        return render_to_response('enterprise/facilities/storage/storageAreaList.html', { 'sas':sas, 'paginator':paginator } ,context_instance=RequestContext(request))

@csrf_exempt
def storageAreaAdd(request):
    _enterPrise = request.session.get('ep')
    if request.method == 'GET':
        return render_to_response('enterprise/facilities/storage/storageAreaAdd.html', context_instance=RequestContext(request))

    if request.method == 'POST':
        sa = StorageArea()
        auto_wear(request, sa, 'enterprise_facilities', 'StorageArea')

        key = request.GET.get('key',None)

        if not key:
            sa.submit_type = 2
        else:
            sa.submit_type = 1

        fill = request.session.get('fill', None)
        app_k = 'S'
        app_name = u'贮罐区'
        app_s = Application_status.objects.filter(app_name=app_name, fill_id = fill.id)

        if len(app_s) > 0:
            app_s = app_s[0]
            app_s.app_status = u'未确认'
            app_s.save()
        else:
            app_s = Application_status(app_name=app_name, fill_id = fill.id, app_status=u'未确认', app_key=app_k, app_submit_time=datetime.datetime.now(), enterprise=_enterPrise)
            app_s.save()

        sa.app_status = app_s
        sa.enterprise = _enterPrise
        sa.save()

        checkAppStatus(request, 2)
        return HttpResponseRedirect('/facilities/storageAreaList/')

@csrf_exempt
def storageAreaEdit(request, id):
    _enterPrise = request.session.get('ep')
    if request.method == 'GET':
        sa = StorageArea.objects.get(id = id)
        return render_to_response('enterprise/facilities/storage/storageAreaAdd.html', { 'sa':sa }, context_instance=RequestContext(request))

    if request.method == 'POST':
        sa = StorageArea.objects.get(id = id)
        auto_wear(request, sa, 'enterprise_facilities', 'StorageArea')

        key = request.GET.get('key',None)

        if not key:
            sa.submit_type = 2
        else:
            sa.submit_type = 1

        sa.enterprise = _enterPrise
        sa.save()

        checkAppStatus(request, 2)
        return HttpResponseRedirect('/facilities/storageAreaDetail/%s' % sa.id)

def storageAreaDetail(request, id):
    try:
        sa = StorageArea.objects.get(id = id)

        sts = StorageTank.objects.filter(storage_area = sa.id)

        paginator = Paginator(sts, 10)
        page = request.GET.get('page')
        sts = paginator.page(page)
    except PageNotAnInteger:
        sts = paginator.page(1)
    except EmptyPage:
        sts = paginator.page(paginator.num_pages)
    except Exception as e:
        return HttpResponse("非法请求\n\n"+ e.message)

    return render_to_response('enterprise/facilities/storage/storageAreaDetail.html', { 'sa':sa, 'sts':sts }, context_instance=RequestContext(request))

@transaction.commit_on_success
def storageAreaDel(request, id):
    try:
        s = StorageArea.objects.get(id = id)
        sts = StorageTank.objects.filter(storage_area = s.id)

        for st in sts:
            st.delete()

        s.delete()

        checkAppStatus(request, 2)
        return HttpResponseRedirect('/facilities/storageAreaList/')

    except Exception,e:
        transaction.rollback()
        result = {'error':e.message if '' else (e.__str__()) }
        return HttpResponse(simplejson.dumps(result))

def storageAreaItems(request, id):
    if request.method == "GET":
        try:
            sts = StorageTank.objects.filter(storage_area = id)

            paginator = Paginator(sts, 10)
            page = request.GET.get('page')
            sts = paginator.page(page)
        except PageNotAnInteger:
            sts = paginator.page(1)
        except EmptyPage:
            sts = paginator.page(paginator.num_pages)
        except Exception as e:
            return HttpResponse("非法请求\n\n"+ e.message)

        return render_to_response('enterprise/facilities/storage/storageList.html', { 'sts':sts, 'paginator':paginator, 'pid':id } ,context_instance=RequestContext(request))

def storageList(request, id):
    _enterPrise = request.session.get('ep')
    if request.method == "GET":

        try:
            sts = StorageTank.objects.filter(storage_area = id)

            paginator = Paginator(sts, 10)
            page = request.GET.get('page')
            sts = paginator.page(page)
        except PageNotAnInteger:
            sts = paginator.page(1)
        except EmptyPage:
            sts = paginator.page(paginator.num_pages)
        except Exception as e:
            return HttpResponse("非法请求\n\n"+ e.message)
        return render_to_response('enterprise/facilities/storage/storageList.html', { 'sts':sts,  'paginator':paginator } ,context_instance=RequestContext(request))

@csrf_exempt
def storageAdd(request, id):
    _enterPrise = request.session.get('ep')
    if request.method == 'GET':
        return render_to_response('enterprise/facilities/storage/storageEdit.html', context_instance=RequestContext(request))

    if request.method == 'POST':
        st = StorageTank()
        auto_wear(request, st, 'enterprise_facilities', 'StorageTank')
        st.storage_area = StorageArea.objects.get(id = id)
        st.save()
        return HttpResponseRedirect('/facilities/storageAreaDetail/%s' % st.storage_area.id)

@csrf_exempt
def storageEdit(request, id):
    _enterPrise = request.session.get('ep')
    if request.method == 'GET':
        st = StorageTank.objects.get(id = id)
        return render_to_response('enterprise/facilities/storage/storageEdit.html', { 'st':st }, context_instance=RequestContext(request))

    if request.method == 'POST':
        st = StorageTank.objects.get(id = id)
        auto_wear(request, st, 'enterprise_facilities', 'StorageTank')
        st.save()
        return HttpResponseRedirect('/facilities/storageAreaDetail/%s' % st.storage_area.id)

def storageDetail(request, id):
    st = StorageTank.objects.get(id = id)
    return render_to_response('enterprise/facilities/storage/storageDetail.html', {'st':st }, context_instance=RequestContext(request))

def storageDel(request, id):
    st = StorageTank.objects.get(id = id)
    st.delete()
    return HttpResponseRedirect('/facilities/storageAreaDetail/%s' % st.storage_area.id)
